﻿#include "ddumsgtest.h"
#include "qdebug.h"
#include "ui_ddumsgtest.h"
#include "Thread/trdptestthread.h"
#include <qfiledialog.h>
#include <QMessageBox>
#include <QScrollBar>
#include <Tool/openxlsxhelper.h>
#include "dialogselectheader.h"
#include"Tool/qxlsxhelper.h"
#include"dialogprotocalconfig.h"
#include"Tool/MsgGenerate.h"
#include"Tool/qfilehelper.h"
#include"Common/pch.h"
DDUMsgTest::DDUMsgTest(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DDUMsgTest)
{
    ui->setupUi(this);
    InitUI();

    if(thread==nullptr)
        thread = new trdpTestThread();
    if (websocketClient == nullptr)
    {
        websocketClient = new WebsocketClient(QUrl(), nullptr);
    }

    connect(thread,&trdpTestThread::SendOCRMdg,this,&DDUMsgTest::OnStartOCR);
    connect(thread,&trdpTestThread::SendProcedureMsg,this,&DDUMsgTest::OnProcedureMsg);
    connect(websocketClient,&WebsocketClient::ReveiveImg,this,&DDUMsgTest::OnReceiveOCRImg);
    connect(thread,&trdpTestThread::WorkFinish,this,&DDUMsgTest::OnWorkFinish);

    ConnectAllSlots();
    ConfigWindowsSplit();
}

DDUMsgTest::~DDUMsgTest()
{
    thread->Stop();
    delete thread;
    //清除申请对象
    websocketClient->closeWebsocket();
    delete websocketClient;

    if(_configTRDP!=nullptr)
        delete _configTRDP;
    delete ui;
}


void DDUMsgTest::InitUI()
{
    ui->pushButton_pause->setEnabled(false);
}


bool DDUMsgTest::loadDataofDDU(QString strFileName)
{
    xlsxhelper.OpenXLSXFile(strFileName);
    DialogProtocalConfig config;
    QStringList sheetNames =xlsxhelper.GetSheetNames();
    config.SetSheetName(sheetNames);
    int SheetResult= config.exec();
    if(SheetResult==QDialog::Accepted)
    {
        _protocalSheetName = config._selectItem;

        return true;
    }
    else
    {
        return false;
    }
}

void DDUMsgTest::Readconfig(const QString &configSheetName)
{
    _trdpCongigs.clear();

    xlsxhelper.SetCurrentSheetName(configSheetName);
    xlsxhelper.ReadHeader();
    xlsxhelper.ReadDataByHeaders();

    //读取配置内容
    QMap<QString,QList<QString>> configdata;
    xlsxhelper.GetUsefulData(configdata);
    int nmaxRow=xlsxhelper.GetDataMaxRow(configdata);

    TRDPconfig tempConfig;
    for(int i=0;i<nmaxRow;i++)
    {
        //和excel字段对应且固定
        tempConfig.ncomid= configdata["comid"][i].toInt();
        tempConfig.niface= configdata["iface"][i].toInt();
        tempConfig.nDataSetSize= configdata["datasetsize"][i].toInt();
        tempConfig.strSourceIP= configdata["sourceip"][i].toStdString();
        tempConfig.strDestIP= configdata["destip"][i].toStdString();
        tempConfig.npdcircle= configdata["circle"][i].toInt();

        _trdpCongigs.append(tempConfig);
        QString str = QString(tempConfig.ToJsonString().c_str());
        emit SendLogMsg(str,0);
    }

}

void DDUMsgTest::ConnectAllSlots()
{

}

void DDUMsgTest::ConfigWindowsSplit()
{
    int width =this->size().width()/2;
    ui->tableWidget_process->resize(width,ui->tableWidget_process->height());
}


void DDUMsgTest::on_pushButton_loadExcel_clicked()
{

    QString fileName = QFileHelper::FileSelect();

    bool bload= false;
    if(!fileName.isEmpty())
        bload=loadDataofDDU(fileName);

    if(bload)
    {
        //读取下发配置
//        Readconfig(_configSheetName);   //读取配置

        //读取数据内容
        xlsxhelper.SetCurrentSheetName(_protocalSheetName);
        xlsxhelper.ReadHeader();
        DialogSelectHeader dialogHeaderSel;
        dialogHeaderSel.SetListHeader(xlsxhelper.GetHeaders());
        int nresult = dialogHeaderSel.exec();
        if(nresult==QDialog::Accepted)
        {

            auto selecedheaders = dialogHeaderSel.GetSelectHeaders();
            xlsxhelper.SetHeader(selecedheaders);
            xlsxhelper.ReadDataByHeaders();

        }

        //显示筛选读取结果
        DDUProtocalData.clear();
        xlsxhelper.GetUsefulData(DDUProtocalData);

        showDDUProtocal(DDUProtocalData);
        int maxRow =  xlsxhelper.GetDataMaxRow(DDUProtocalData);
        _statusInfo.setItemCount(maxRow);
        emit SendStatusInfo(_statusInfo);

        //缓存打开文件名到配置类
        QFileInfo fileInfo(fileName);
        ConfigData::strProtocalName=fileInfo.baseName();
        qDebug()<<ConfigData::strProtocalName<<endl;
        emit SendLogMsg(QString::fromLocal8Bit("打开excel:")+fileName,0);

    }

}

void DDUMsgTest::on_pushButton_PDFExport_clicked()
{


}

void DDUMsgTest::on_pushButton_pause_clicked()
{
    if(ui->pushButton_pause->text()==QString::fromLocal8Bit("暂停测试"))
    {
        thread->SetWorkFinishCode(1);
        websocketClient->closeWebsocket();
        if(thread!=nullptr)
            thread->Stop();
        ui->pushButton_pause->setText(QString::fromLocal8Bit("继续"));
        _statusInfo.pause();
        //等待线程执行完成
        ui->pushButton_pause->setEnabled(false);


    }
    else if(ui->pushButton_pause->text()==QString::fromLocal8Bit("继续"))
    {
        websocketClient->SetURL(ConfigData::snapURL);
        websocketClient->openWebsocket();
        bool bconnect= websocketClient->isConnected();
        if(!bconnect)
        {
            emit SendLogMsg(QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。"));
            return ;
        }
        thread->start();
        ui->pushButton_pause->setText(QString::fromLocal8Bit("暂停测试"));
        _statusInfo.continueCount();
    }
}

void DDUMsgTest::on_pushButton_Start_clicked()
{
    if(DDUProtocalData.isEmpty())
    {
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("请先加载DDU配置"));
        return;
    }
    //清除第一行测试结果
    ui->pushButton_pause->setEnabled(true);

    websocketClient->SetURL(ConfigData::snapURL);
    websocketClient->openWebsocket();
    bool bconnect= websocketClient->isConnected();
    if(!bconnect)
    {
        emit SendLogMsg(QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。"));
        return ;
    }

    thread->SetTestData(DDUProtocalData,0);

    connect(thread,&trdpTestThread::SignalTestResult,this,&DDUMsgTest::OnStepFinish);
    thread->start();


    ui->pushButton_Start->setEnabled(false);

    //状态以及计时
    _statusInfo.setWorkStatus(true);
    _statusInfo.setItemCount(thread->GetMaxRowOfData());
    _statusInfo.start(100);

}

//步骤完成
void DDUMsgTest::OnStepFinish(int id, bool bResult,QString testInfo)
{
    auto item1=new QTableWidgetItem();
    auto item2=new QTableWidgetItem();

    if(bResult)
    {
        item1->setIcon(QIcon(":/Icon/icon_32/zhengque.svg"));
        item2->setText(testInfo);

    }
    else
    {
        item1->setIcon(QIcon(":/Icon/icon_32/error.svg"));
        item2->setText(QString(testInfo));

    }
    ui->tableWidget_process->setItem(id,0,item1);
    ui->tableWidget_process->setItem(id,1,item2);


    QScrollBar * scrollbar = ui->tableWidget_process->verticalScrollBar();
    if(scrollbar)
    {
        if(id<scrollbar->maximum())
        {
            if(id>_nShowLine)
                scrollbar->setSliderPosition(id-_nShowLine);
        }
        else
        {
            scrollbar->setSliderPosition(scrollbar->maximum());
        }
    }

    _statusInfo.setID(id);

}

void DDUMsgTest::OnReceiveOCRImg(QByteArray byteArray)
{
    QPixmap pixmap;
    pixmap.loadFromData(byteArray);
    ui->scrollAreaWidgetContents->setMinimumSize( pixmap.width(), pixmap.height());
    ui->labelImgtrdp->setImage(pixmap);
    //保存原图图片路径 选择路径 +加载文件名+Origion
    if(ConfigData::bSaveOrigion)
    {
        QString strOrigion = ConfigData::imgSavePath+"/"+ConfigData::strProtocalName+"/"+"Origion"+"/";
        QDir dir(strOrigion);
        if(!dir.exists())
            dir.mkdir(strOrigion);

        int nid= thread->GetIndex()+1;
        QString strID=QString::number(nid);
        QString strexportFormat =".png" ;
        QString filename = strOrigion+strID+strexportFormat;
        qDebug()<<"origion filename:"<<filename<<endl;
        pixmap.save(filename);
    }

    if(!bSnap&&thread!=nullptr)
    {
        thread->acceptImg( ui->labelImgtrdp->GetRectImg());
    }

    if(bSnap)
    {
        websocketClient->closeWebsocket();
        bSnap=false;
        ui->pushButton_Snap->setEnabled(true);
        emit SendLogMsg("receive img");

    }
}


void DDUMsgTest::on_pushButton_stop_clicked()
{
    websocketClient->closeWebsocket();
    if(thread!=nullptr)
    {
        thread->SetWorkFinishCode(2);
        thread->Stop();
        thread->SetIndex(0);
    }

    //暂停只在工作时有效
    ui->pushButton_pause->setEnabled(false);
    _statusInfo.setWorkStatus(false);

}


void DDUMsgTest::OnStartOCR()
{
    websocketClient->screenShot();

}

void DDUMsgTest::OnProcedureMsg(const QString &msg)
{
    emit SendLogMsg(msg);
}

void DDUMsgTest::OnStatusInfoUpdate(int nid,QTime& time,bool bWork)
{
    //更新测试结果
}


//在tablewidget中显示协议
void DDUMsgTest::showDDUProtocal(const QMap<QString, QList<QString> > &DDUProtocal)
{

    int ncolumnCount =DDUProtocal.keys().size()+2;
    int nrowcount =xlsxhelper.GetDataMaxRow(DDUProtocal);
    ui->tableWidget_process->clear();
    ui->tableWidget_process->setRowCount(nrowcount);
    ui->tableWidget_process->setColumnCount(ncolumnCount);//先设置列数才能进行显示

    QStringList headers=DDUProtocal.keys();
    headers.push_front(QString::fromLocal8Bit("测试描述"));
    headers.push_front(QString::fromLocal8Bit("测试结果"));
    ui->tableWidget_process->setHorizontalHeaderLabels(headers);
    ui->tableWidget_process->setAlternatingRowColors(true);

    int nColumn=2;
    for (auto iter = DDUProtocal.begin(); iter!=DDUProtocal.end() ; ++iter)
    {
        for (int row = 0; row < nrowcount; ++row)
        {

            auto& tempdata = iter.value()[row];
            QTableWidgetItem *newItem = new QTableWidgetItem(tempdata);
            ui->tableWidget_process->setItem(row, nColumn, newItem);


        }
        nColumn++;
    }


    ui->tableWidget_process->resizeColumnsToContents();
}


void DDUMsgTest::on_pushButton_Snap_clicked()
{
    bSnap=true;
    if(websocketClient==nullptr)
        emit SendLogMsg("websocket is null");
    websocketClient->SetURL(ConfigData::snapURL);
    websocketClient->openWebsocket();
    bool bconnect= websocketClient->isConnected();
    if(!bconnect)
    {
        qDebug()<<QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。")<<endl;
        emit SendLogMsg(QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。"));
        return ;
    }
    websocketClient->screenShot();
    emit SendLogMsg("snap");

    ui->pushButton_Snap->setEnabled(false);
}

void DDUMsgTest::OnWorkFinish(int ncode)
{
    if(ncode==0)
    {
        ui->pushButton_Start->setEnabled(true);

    }
    else if(ncode==1)
    {
        ui->pushButton_pause->setEnabled(true);

    }
    else
    {
        ui->pushButton_Start->setEnabled(true);
        ui->pushButton_pause->setEnabled(true);
    }
}


void DDUMsgTest::on_pushButton_configTRDP_clicked()
{
    if(_configTRDP==nullptr)
    {
        _configTRDP = new FormConfigTRDP();
        _configTRDP->SetTCPServerInfo(ConfigData::strIP,ConfigData::strPort);
    }
    _configTRDP->show();
}


void DDUMsgTest::on_pushButton_OCRtest_clicked()
{
//    std::string filePath ="C:/image/PM222G61312-滁宁DDU系统/Error/35.png";
    auto  test = ui->labelImgtrdp->GetRectImages();
    if(test.empty())
    {
        emit SendLogMsg("没有图像数据");
        return;
    }

    PaddleOCR::PPOCR ppocr;         //OCR对象
    QStringList list;

    for (auto iter = test.begin(); iter != test.end(); ++iter)
    {
        auto ocr_result =ppocr.ocr(iter.value(),true,true,false);
        for (int i = 0; i < ocr_result.size(); ++i)
        {
            list<<ocr_result[i].text.c_str();

        }
    }

    emit SendLogMsg("总识别数"+QString::number(list.count()));



    //    6.发送数据与结果比对
//    for (int i = 0; i < ocr_result.size(); ++i)
//    {
//        list<<ocr_result[i].text.c_str();
//        int nbox = ocr_result[i].box.size();
//        QString str =QString::number(nbox);
//        emit SendLogMsg("OCR Box count:"+str);

//        for (int j = 0; j < ocr_result[i].box.size(); ++j)
//        {
//            auto boxn = ocr_result[i].box[j];
//            QStringList strBoxinfo;
//            for (auto m=0;m<boxn.size();m++)
//            {
//                strBoxinfo<<QString::number(boxn[m]);
//            }
//            emit SendLogMsg("OCR Box info:"+strBoxinfo.join(","));
//        }
//    }
    emit SendLogMsg("OCR Result:"+list.join(","));
}

void DDUMsgTest::SlotReceiveTcpServerReply(const QString &msg)
{
    QString strReceive = QString::fromLocal8Bit("返回消息：%1").arg(msg);
    emit SendLogMsg(strReceive);
}

